Telegram Group & Telegram Channel
Сегодня я покажу вам, как быстро и удобно организовать автозагрузку классов в PHP без использования Composer.

Мы все любим Composer, но бывают ситуации, когда он просто неуместен — например, в небольшом проекте, скрипте или легаси-коде, где Composer не использовался изначально. В таких случаях можно сделать свою простую, но эффективную автозагрузку.

Вот базовый пример:


spl_autoload_register(function ($class) {
$baseDir = __DIR__ . '/src/';
$classPath = str_replace('\\', '/', $class) . '.php';
$file = $baseDir . $classPath;

if (file_exists($file)) {
require $file;
}
});


Что здесь происходит:
- spl_autoload_register регистрирует анонимную функцию, которая будет вызываться при попытке использовать неизвестный класс.
- Класс App\Services\MailService превратится в путь src/App/Services/MailService.php
- Если файл существует — он подключается.

Это суперудобный способ структурировать код и избавиться от бесконечных require.

Если хочется чуть больше гибкости — можно добавить поддержку нескольких базовых директорий, логирование ошибок или даже кэширование найденных путей.

Вопрос к вам:
А вы когда-нибудь писали свою автозагрузку? Или полностью доверяете Composer?

👉 @php_lib



tg-me.com/php_lib/748
Create:
Last Update:

Сегодня я покажу вам, как быстро и удобно организовать автозагрузку классов в PHP без использования Composer.

Мы все любим Composer, но бывают ситуации, когда он просто неуместен — например, в небольшом проекте, скрипте или легаси-коде, где Composer не использовался изначально. В таких случаях можно сделать свою простую, но эффективную автозагрузку.

Вот базовый пример:


spl_autoload_register(function ($class) {
$baseDir = __DIR__ . '/src/';
$classPath = str_replace('\\', '/', $class) . '.php';
$file = $baseDir . $classPath;

if (file_exists($file)) {
require $file;
}
});


Что здесь происходит:
- spl_autoload_register регистрирует анонимную функцию, которая будет вызываться при попытке использовать неизвестный класс.
- Класс App\Services\MailService превратится в путь src/App/Services/MailService.php
- Если файл существует — он подключается.

Это суперудобный способ структурировать код и избавиться от бесконечных require.

Если хочется чуть больше гибкости — можно добавить поддержку нескольких базовых директорий, логирование ошибок или даже кэширование найденных путей.

Вопрос к вам:
А вы когда-нибудь писали свою автозагрузку? Или полностью доверяете Composer?

👉 @php_lib

BY Библиотека PHP программиста 👨🏼‍💻👩‍💻




Share with your friend now:
tg-me.com/php_lib/748

View MORE
Open in Telegram


Библиотека PHP программиста ‍‍ Telegram | DID YOU KNOW?

Date: |

Telegram and Signal Havens for Right-Wing Extremists

Since the violent storming of Capitol Hill and subsequent ban of former U.S. President Donald Trump from Facebook and Twitter, the removal of Parler from Amazon’s servers, and the de-platforming of incendiary right-wing content, messaging services Telegram and Signal have seen a deluge of new users. In January alone, Telegram reported 90 million new accounts. Its founder, Pavel Durov, described this as “the largest digital migration in human history.” Signal reportedly doubled its user base to 40 million people and became the most downloaded app in 70 countries. The two services rely on encryption to protect the privacy of user communication, which has made them popular with protesters seeking to conceal their identities against repressive governments in places like Belarus, Hong Kong, and Iran. But the same encryption technology has also made them a favored communication tool for criminals and terrorist groups, including al Qaeda and the Islamic State.

Tata Power whose core business is to generate, transmit and distribute electricity has made no money to investors in the last one decade. That is a big blunder considering it is one of the largest power generation companies in the country. One of the reasons is the company's huge debt levels which stood at ₹43,559 crore at the end of March 2021 compared to the company’s market capitalisation of ₹44,447 crore.

Библиотека PHP программиста ‍‍ from us


Telegram Библиотека PHP программиста 👨🏼‍💻👩‍💻
FROM USA